package com.shop.api;

import com.shop.api.params.CreateOrderParam;
import com.shop.api.params.CreateProductParam;
import com.shop.config.annotation.TokenToUser;
import com.shop.entity.User;
import com.shop.service.OrderService;
import com.shop.util.Result;
import com.shop.util.ResultGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/order")
public class OrderApi {

    @Resource
    private OrderService orderService;

    @PostMapping("/createOrder")
    public Result createProduct(@RequestBody List<CreateOrderParam> createOrderParam, @TokenToUser User loginUser) {
        if (loginUser == null) {
            return ResultGenerator.genFailResult(50003);//token失效
        }

        int result = 50070;

        for (CreateOrderParam c : createOrderParam) {
            result = orderService.createOrder(loginUser.getUserId(),
                    c.getStoreId(),
                    c.getAddress(),
                    c.getInfo());
            if (result != 20000) {
                return ResultGenerator.genFailResult(result);
            }
        }
        if (result == 20000) {
            log.info("成功创建{}个订单", createOrderParam.size());
            return ResultGenerator.genSuccessResult();
        }
        return ResultGenerator.genFailResult(result);
    }

    @PostMapping("/searchOrder")
    public Result getOrder(@RequestParam Long orderId, @TokenToUser User loginUser) {
        if (loginUser == null) {
            return ResultGenerator.genFailResult(50003);//token失效
        }
        Map result = orderService.searchOrder(orderId);
        if (result.size() != 0) {
            log.info("查询订单{}", result.toString());
            return ResultGenerator.genSuccessResult(result);
        }

        return ResultGenerator.genFailResult(50071);
    }

    @PostMapping("/searchUserOrder")
    public Result getOrder(@TokenToUser User loginUser) {
        if (loginUser == null) {
            return ResultGenerator.genFailResult(50003);//token失效
        }
        List result = orderService.searchUserAllOrder(loginUser);
        if (result.size() != 0) {
            log.info("查询用户{}的订单", loginUser.getUsername());
            return ResultGenerator.genSuccessResult(result);
        }

        return ResultGenerator.genFailResult(50071);
    }

    @PostMapping("/changeStatus")
    public Result changeStatus(@RequestParam Long orderId, @RequestParam int status, @TokenToUser User loginUser) {
        if (loginUser == null) {
            return ResultGenerator.genFailResult(50003);//token失效
        }

        int result = orderService.changeStatus(orderId, status);
        if (result == 20000) {
            return ResultGenerator.genSuccessResult();
        }
        return ResultGenerator.genFailResult(result);
    }


}
